package com.city.ajax.auth;

import com.city.domain.auth.AuthLevelOne;
import com.city.domain.auth.AuthLevelPub;
import com.city.domain.auth.PubAuth;
import com.city.domain.auth.format.CtBranchFormat;
import com.city.domain.pub.PubUser;
import com.city.domain.report.CtBranch;
import com.city.domain.report.CtUser;
import com.city.domain.report.CtUserBranch;
import com.city.domain.report.format.CtUserFoemat;
import com.city.repository.report.CtBranchFormatRepository;
import com.city.repository.report.CtUserBranchRepository;
import com.city.repository.report.CtUserRepository;
import com.city.repository.report.format.CtUserFoematRepository;
import com.city.service.auth.AuthLevelPubService;
import com.city.service.auth.PubAuthService;
import com.city.service.pub.PubUserService;
import com.city.service.report.CtBranchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/ajax/auth")
public class AuthAjax {

    @Autowired
    private PubUserService userService;

    @Autowired
    private PubAuthService pubAuthwService;

    @Autowired
    private CtBranchService branchService;

    @Autowired
    private AuthLevelPubService authLevelPubService;

    @Autowired
    private CtBranchFormatRepository ctBranchFormatRepository;

    @Autowired
    private CtUserRepository ctUserRepository;

    @Autowired
    private CtUserFoematRepository ctUserFoematRepository;

    @Autowired
    private CtUserBranchRepository ctUserBranchRepository;





    @PostMapping("/personlist")
    @ResponseBody
    public Map<String,Object> personList(@Param("page") Integer page,
                                         @Param("limit") Integer limit){
        Map<String,Object> map = new HashMap<>();
        List<PubUser> userList = userService.findByAuthLimit(page, limit);
        map.put("code",0);
        map.put("data",userList);
        map.put("msg","成功");
        map.put("count",userService.count());
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/1
     * @description  查看单个权限
     */
    @PostMapping("/getOneAuth")
    @ResponseBody
    public Map<String,Object> getOneAuth(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();
        System.out.println(id);
        PubAuth pubAuth = pubAuthwService.findByUserId(id);
        System.out.println();
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/8/31
     * @description  部门列表
     */
    @PostMapping("/branchlist")
    @ResponseBody
    public Map<String,Object> branchList(@Param("page") Integer page,
                                         @Param("limit") Integer limit) {
        Map<String,Object> map = new HashMap<>();
        List<CtBranchFormat> branchList = ctBranchFormatRepository.findByFormatLimit((page-1)*limit,limit);
        System.out.println(branchList.size());



        map.put("code",0);
        map.put("data",branchList);
        map.put("msg","成功");
        map.put("count",branchService.count());
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/8/31
     * @description  登录验证
     */
    @PostMapping("/login")
    @ResponseBody
    public Map<String,Object> login(@Param("account") String account,
                                    @Param("password") String password,
                                    HttpSession session){
        Map<String,Object> map = new HashMap<>();
        if(account.equals("admin") && password.equals("admin")){
            session.setAttribute("user","admin");
            map.put("code",0);
            map.put("msg","登录成功!");

        }else {
            map.put("code",-1);
        }

        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/1
     * @description  部门详细信息
     */
    @PostMapping("/getOneBranch")
    @ResponseBody
    public Map<String,Object> getOneBranch(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();


        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/1
     * @description  保存权限
     */
    @PostMapping("/addAuthsValue")
    @ResponseBody
    public Map<String,Object> saveAuths(@Param("auths") String auths,
                                        @Param("id") int id,
                                        @Param("authsName") String authsName){
        Map<String,Object> map = new HashMap<>();

        //判断数据库中是否已经存在此userid的权限
        PubAuth pubAuth = pubAuthwService.findByUserId(id);

        Integer shiyan = checjkAuthIndex(auths,id);
        if(shiyan == 1){
            if(null == pubAuth){
                //执行添加操作
                //添加公共权限
                AuthLevelPub authLevelPub = authLevelPubService.findById(1);

                auths = auths + authLevelPub.getValue();

                //拿到user_id  和权限 并保存
                PubAuth auth = new PubAuth();
                auth.setUserId(id);
                auth.setValue(auths);
                auth.setNames(authsName);
                pubAuthwService.save(auth);

                map.put("code",0);
                map.put("msg","保存成功");
            }else{
                //执行更新操作
                //拿到user_id  和权限 并保存

                AuthLevelPub authLevelPub = authLevelPubService.findById(1);

                auths = auths + authLevelPub.getValue();

                PubAuth auth = new PubAuth();
                auth.setUserId(id);
                auth.setId(pubAuth.getId());
                auth.setValue(auths);
                auth.setNames(authsName);
                pubAuthwService.save(auth);
                map.put("code",0);
                map.put("msg","保存成功");
            }
        } else {
            map.put("code",-1);
        }

        return map;
    }

    public Integer checjkAuthIndex(String auths,Integer id){

        CtUser ctUser = ctUserRepository.findOne(id);
        if(ctUser != null){
            String[] authArr = auths.split(",");
            if(Arrays.asList(authArr).contains("/business/index")){
                ctUser.setBusinessIndex(1);
            }else {
                ctUser.setBusinessIndex(null);
            }

            if(Arrays.asList(authArr).contains("/colligate/index")){
                ctUser.setColligateIndex(1);
            }else {
                ctUser.setColligateIndex(null);
            }

            if(Arrays.asList(authArr).contains("/command/index")){
                ctUser.setCommandIndex(1);
            }else {
                ctUser.setCommandIndex(null);
            }

            if(Arrays.asList(authArr).contains("/grid/index")){
                ctUser.setGridIndex(1);
            }else {
                ctUser.setGridIndex(null);
            }

            if(Arrays.asList(authArr).contains("/house/index")){
                ctUser.setHouseIndex(1);
            }else {
                ctUser.setHouseIndex(null);
            }

            if(Arrays.asList(authArr).contains("/special/index")){
                ctUser.setSpecialIndex(1);
            }else {
                ctUser.setSpecialIndex(null);
            }

            if(Arrays.asList(authArr).contains("/supervise/index")){
                ctUser.setSuperviseIndex(1);
            }else {
                ctUser.setSuperviseIndex(null);
            }

            if(ctUser.getIsManager() != null){
                ctUser.setAuthIndex(1);
            }else {
                ctUser.setAuthIndex(null);
            }

            return 1;
        }
        return 0;
    }

    /**
     * @author  王宇
     * @date 2018/9/1
     * @description  获取某人的权限
     */
    @PostMapping("/getAuthAndName")
    @ResponseBody
    public Map<String,Object> getAuthAndName(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();

        //从数据库中获取权限
        PubAuth pubAuth = pubAuthwService.findByUserId(id);



        //减掉公共权限

        AuthLevelPub authLevelPub = authLevelPubService.findById(1);

        String auths = pubAuth.getValue().replace(authLevelPub.getValue(),"").trim();
        String[] authArr = auths.split(",");
        String[] nameArr = pubAuth.getNames().split(",");
        map.put("code",0);
        map.put("auths",authArr);
        map.put("names",nameArr);
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/2
     * @description  搜索
     */
    @PostMapping("/searchUser")
    @ResponseBody
    public Map<String,Object> searchUser(@Param("idCard") String idCard,
                                         @Param("userId") int userId){
        Map<String,Object> map = new HashMap<>();

        System.out.println(userId);
        System.out.println(idCard);

        if((null==idCard || ""==idCard) && userId != 0){
            //只传了id  根据id查询
            PubUser pubUser = userService.findById(userId);
            List<PubUser> list = new ArrayList<>();
            list.add(pubUser);
            map.put("code",0);
            map.put("data",list);
            map.put("count",1);

        }else if(0==userId && (null!=idCard || ""!=idCard)){
            //只传了idCard
            PubUser pubUser = userService.getUserByIdCard(idCard);
            List<PubUser> list = new ArrayList<>();
            list.add(pubUser);
            map.put("code",0);
            map.put("data",list);
            map.put("count",1);


        }else if(0!=userId && (null!=idCard || ""!=idCard)){

            //两个都传了
            PubUser pubUser = userService.findByIdCardAndId(idCard,userId);
            List<PubUser> list = new ArrayList<>();
            list.add(pubUser);
            map.put("code",0);
            map.put("data",list);
            map.put("count",1);
        }else {
            map.put("code",-1);
            map.put("msg","没有找到哦！");
        }
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/2
     * @description  部门详细信息
     */
    @PostMapping("/branchInfo")
    @ResponseBody
    public Map<String,Object> branchInfo(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();
        CtBranchFormat ctBranchFormat = ctBranchFormatRepository.findById(id);
        map.put("code",0);
        map.put("data",ctBranchFormat);
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/2
     * @description  获取部门
     */
    @PostMapping("/branches")
    @ResponseBody
    public Map<String,Object> branches(@Param("check") int check){
        Map<String,Object> map = new HashMap<>();
        if(check==1024){
            List<CtBranch> branchList = branchService.findAll();
            map.put("code",0);
            map.put("data",branchList);
        }
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/9/2
     * @description  保存 更新部门信息
     */
    @PostMapping("/saveBranch")
    @ResponseBody
    public Map<String,Object> saveBranch(@Param("check") int check,
                                         @RequestBody CtBranch ctBranch){
        Map<String,Object> map = new HashMap<>();
        //通过check判断是添加操作，修改操作
        if(check == 1024){
            //添加操作
            branchService.save(ctBranch);
            map.put("code",0);
            map.put("msg","添加成功");
        }else {
            //修改操作，此时check是id
            ctBranch.setId(check);
            branchService.save(ctBranch);
            map.put("code",0);
            map.put("msg","修改成功");
        }

        return map;
    }


    /**
     * @author  王宇
     * @date 2018/9/2
     * @description  删除部门信息
     */
    @PostMapping("/deletebranch")
    @ResponseBody
    public Map<String,Object> deleteBranch(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();
        //通过id删除对象
        branchService.delete(id);

        map.put("code",0);
        map.put("msg","删除成功！");
        return map;
    }

    /**
     * @author  王宇
     * @date 2018/10/6
     * @description  人员列表
     */
    @PostMapping("/branch_person_list")
    @ResponseBody
    public Map<String,Object> branchPersonlIst(@Param("page") Integer page,
                                               @Param("limit") Integer limit){
        Map<String,Object> map = new HashMap<>();
        List<CtUserFoemat> ctUserFoemats = ctUserFoematRepository.findByPage((page-1)*limit,limit);
        map.put("data",ctUserFoemats);
        map.put("count",ctUserRepository.count());
        map.put("code",0);
        map.put("msg","成功");
        return map;
    }


    /**
     * @Author: 李顺时
     * @Description: 添加管理人员或者修改管理人员
     * @Date: 17:58 2018/10/6
     */
    @PostMapping("/savePersonList")
    @ResponseBody
    @Transactional
    public Map<String,Object> savePersonList(@Param("check") int check,
                                         @Param("username") String username,
                                         @Param("password") String password,
                                         @Param("branchId") Integer branchId,
                                         @Param("manage") Integer manage
                                         ){
        Map<String,Object> map = new HashMap<>();
        //通过check判断是添加操作，修改操作
        if(check == 1024){
            //添加操作
            CtUser ctUser= new CtUser();
            System.out.println(manage);
            if(ctUserRepository.findByName(username)!=null){
                map.put("code",-1);
                map.put("msg","账号已存在");
                return map;
            }
            if(manage ==1){
                ctUser.setIsManager(1);
            }else{

            }
            ctUser.setName(username);
            ctUser.setPassword(password);
            ctUserRepository.save(ctUser);
            CtUser ctUser1 = ctUserRepository.findByNameAndPassword(username,password);
            if(ctUser1!=null){
                CtUserBranch ctUserBranch = new CtUserBranch();
                ctUserBranch.setUserId(ctUser1.getId());
                ctUserBranch.setBranchId(branchId);
                ctUserBranchRepository.save(ctUserBranch);
            }else{

            }
            map.put("code",0);
            map.put("msg","添加成功");
        }else {
            //修改操作，此时check是ct_user的id
            CtUser ctUser = new CtUser();
            if(manage ==1){
                ctUser.setIsManager(1);
            }
            ctUser.setId(check);
            ctUser.setName(username);
            ctUser.setPassword(password);
            CtUserBranch ctUserBranch= ctUserBranchRepository.findBranchByUserId(check);
            System.out.println(ctUserBranch);
            ctUserBranch.setBranchId(branchId);
            ctUserRepository.save(ctUser);
            ctUserBranchRepository.save(ctUserBranch);
            map.put("code",0);
            map.put("msg","修改成功");
        }

        return map;
    }

    /**
     * @Author: 李顺时
     * @Description: 修改时的数据查询
     * @Date: 17:57 2018/10/6
     */
    @PostMapping("/ctUserInfo")
    @ResponseBody
    public Map<String,Object> ctUserInfo(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();
        CtUserFoemat ctUserFoemat  = ctUserFoematRepository.findByUserId(id);
        //判断是否为管理员 为空则不是管理员  将其改为0输出到页面
        map.put("code",0);
        map.put("data",ctUserFoemat);
        return map;
    }


    /**
     * @Author: 李顺时
     * @Description: 删除ctUser数据
     * @Date: 17:58 2018/10/6
     */
    @PostMapping("/deleteCtUser")
    @ResponseBody
    @Transactional
    public Map<String,Object> deleteCtUser(@Param("id") int id){
        Map<String,Object> map = new HashMap<>();
        //通过id删除对象
        ctUserRepository.deleteById(id);
        Integer ctUserBranchId= ctUserBranchRepository.findBranchIdByUserId(id);
        ctUserBranchRepository.delete(ctUserBranchId);
        map.put("code",0);
        map.put("msg","删除成功！");
        return map;
    }
}
